#include "rclcpp/rclcpp.hpp" 
#include "origincar_msg/msg/sign.hpp"
#include "sensor_msgs/msg/image.hpp"
#include <opencv2/opencv.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <zbar.h>
#include <vector>
/*
class QRCodeDetector {
public:
    QRCodeDetector() {
        // 初始化微信二维码检测器相关配置
        depro = "/root/lyz_qrcode/detect.prototxt";
        decaf = "/root/lyz_qrcode/detect.caffemodel";
        srpro = "/root/lyz_qrcode/sr.prototxt";
        srcaf = "/root/lyz_qrcode/sr.caffemodel";
    }

    std::string detect(const cv::Mat& img) {
        cv::Mat gray;
        cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
        cv::Ptr<cv::wechat_qrcode::WeChatQRCode> detector =
            cv::wechat_qrcode::WeChatQRCode::create(depro, decaf, srpro, srcaf);

        std::vector<cv::String> barcodes;
        detector->detectAndDecode(gray, barcodes);
        return barcodes.empty() ? "" : barcodes[0];
    }

private:
    std::string depro;
    std::string decaf;
    std::string srpro;
    std::string srcaf;
};
*/
class QrcodeNode : public rclcpp::Node {
public:
    QrcodeNode(const std::string& name) : Node(name) {
        RCLCPP_INFO(this->get_logger(), "大家好，我是发布二维码识别的话题%s", name.c_str());
        publisher_ = this->create_publisher<origincar_msg::msg::Sign>("sign_switch", 10);
        subscription_ = this->create_subscription<sensor_msgs::msg::Image>(
            "/image", 10, std::bind(&QrcodeNode::image_callback, this, std::placeholders::_1));

        //wechat_qr_detector = std::make_shared<QRCodeDetector>();
    }

private:
    void image_callback(const sensor_msgs::msg::Image::SharedPtr msg) {
        try {
            // 将ROS图像消息的原始数据转换为std::vector<uint8_t>
            std::vector<uint8_t> data(msg->data.begin(), msg->data.end());

            // 使用OpenCV解码JPEG图像
            cv::Mat image = cv::imdecode(data, cv::IMREAD_COLOR);

            if (image.empty()) {
                throw std::runtime_error("Failed to decode image.");
            }

            // 裁剪区域
            cv::Mat image_roi = image(cv::Rect(0, 150, 640, 170));

            decode_qr_code_pyzbar(image_roi);
            // decode_qr_code_wechat(image_roi); // 如果要使用WeChatQRCode检测，请取消注释此行

        } catch (const std::exception& e) {
            RCLCPP_ERROR(this->get_logger(), "Error processing image: %s", e.what());
        }
    }

    void decode_qr_code_pyzbar(const cv::Mat& image) {
        // 使用ZBar进行二维码解码
        zbar::ImageScanner scanner;
        scanner.set_config(zbar::ZBAR_NONE, zbar::ZBAR_CFG_ENABLE, 1);
        
        cv::Mat gray;
        cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
        zbar::Image zbar_image(gray.cols, gray.rows, "Y800", (uchar *)gray.data, gray.cols * gray.rows);
        scanner.scan(zbar_image);

        for (zbar::Image::SymbolIterator symbol = zbar_image.symbol_begin(); 
             symbol != zbar_image.symbol_end(); ++symbol) {
            std::string qr_code_data = symbol->get_data();
            if (qr_code_data == "ClockWise" || qr_code_data == "AntiClockWise") {
                publish_sign_message(qr_code_data);
                return; // 成功识别后返回
            }
        }
    }

    void publish_sign_message(const std::string& qr_code_data) {
        origincar_msg::msg::Sign sign_msg;
        sign_msg.sign_data = (qr_code_data == "ClockWise") ? 3 : 4;
        publisher_->publish(sign_msg);
        RCLCPP_INFO(this->get_logger(), "已发布二维码信息: %s", qr_code_data.c_str());
    }

    rclcpp::Publisher<origincar_msg::msg::Sign>::SharedPtr publisher_;
    rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr subscription_;
    // std::shared_ptr<QRCodeDetector> wechat_qr_detector;
};

int main(int argc, char *argv[]) {
    rclcpp::init(argc, argv);
    auto node = std::make_shared<QrcodeNode>("qrcode_cpp");
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}
